package Weapon

import (
	codecs "sanguo/codec/cs"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionDemountWeapon struct {
	transaction.TransactionBase
	user    *user.User
	req     *codecs.Message
	resp    *cs_message.DemountWeaponToC
	errcode cs_message.EnumType
}

func (this *transactionDemountWeapon) GetModuleName() string {
	return "Weapon"
}

func (this *transactionDemountWeapon) GetReplyMsg() proto.Message {
	return &cs_message.DemountWeaponToC{}
}

func (this *transactionDemountWeapon) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionDemountWeapon) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionDemountWeapon) Begin() {

	this.resp = &cs_message.DemountWeaponToC{}
	msg := this.req.GetData().(*cs_message.DemountWeaponToS)
	demountPos := msg.GetDemountPos()

	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()
	if role == nil || !role.IsRoleModleData() {
		node_game.Infoln(role.GetUserID(), "DemountWeapon fail : role is nil")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}
	node_game.Infof("%s %d Call DemountWeapon pos:%d ", role.GetUserID(), role.GetID(), msg.GetDemountPos())

	if demountPos < 1 || demountPos > 2 {
		node_game.Infoln(role.GetUserID(), role.GetID(), "DemountWeapon fail:weapon demountPos fail:", demountPos)
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	demountWeapon := role.GetRoleWeapon().GetWeaponByState(demountPos)
	if demountWeapon == nil {
		node_game.Infoln(role.GetUserID(), role.GetID(), "DemountWeapon fail:Weapon is nil")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	role.GetRoleWeapon().DemountWeapon(demountWeapon.GetWeaponId())

	//change roleData weapon
	if demountPos == 1 {
		role.SetWeapon1(0)

	} else if demountPos == 2 {
		role.SetWeapon2(0)
	}

	//将外观传到map
	role.ChangeOutline()

	//重新计算战斗属性
	role.TotalBattleAttr()

	//发送背包变化
	role.OnWeaponDirty()

	node_game.Infoln(role.GetUserID(), role.GetID(), "DemountWeapon OK")
	this.errcode = cs_message.EnumType_OK
	this.user.EndTrans(this)
}

func (this *transactionDemountWeapon) End() {
	this.resp.Errcode = cs_message.EnumType(this.errcode).Enum()
	this.user.Reply(this.req.GetSeriNo(), this.resp)
}

func (this *transactionDemountWeapon) Timeout() {
	this.resp.Errcode = cs_message.EnumType(cs_message.EnumType_RETRY).Enum()
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.DemountWeaponToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionDemountWeapon{
			user: user,
			req:  msg,
		}
	})
}
